I have the same problem with NavigationLinks (in place of Buttons in the original question). Setting .buttonStyle(.borderless) or .buttonStyle(PlainButtonStyle()) does not fix it. ChatGPT gave me a clear example, which it claimed would work, but just repeats the problem
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
ForEach(0..<10) { index in
HStack {
NavigationLink(destination: DestinationView1(item: index)) {
Text("Navigate to View 1")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.buttonStyle(PlainButtonStyle()) // Ensure the link only activates on its area
Spacer()
NavigationLink(destination: DestinationView2(item: index)) {
Text("Navigate to View 2")
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(8)
}
.buttonStyle(PlainButtonStyle()) // Ensure the link only activates on its area
}
.padding(.vertical, 5)
}
}
.navigationBarTitle("Navigation Links")
}
}
}
struct DestinationView1: View {
var item: Int
var body: some View {
Text("Destination View 1 for item \(item)")
.navigationBarTitle("View 1", displayMode: .inline)
}
}
struct DestinationView2: View {
var item: Int
var body: some View {
Text("Destination View 2 for item \(item)")
.navigationBarTitle("View 2", displayMode: .inline)
}
}
Post
Replies
Boosts
Views
Activity
Hi Claude31, thank you so much for taking the time to reply. I have tried changing to buttons, but it was not successful, as described in another report "Swiftui - Pressing button in a list also actions another button", which you also responded to, suggesting using button style, (which does not fix it). The same problem exists with buttons. I included the ChatGPT code because it illustrates the problem much more concisely than my own code. I really think this is a flaw in SwiftUI, although I am wary of making such a claim. Please could you paste the code above into Xcode and witness the failure. It will only take a minute. I would love to see this code example reach the Swift team. I think they would be surprised, and maybe able to resolve it. Best regards, Denis Stanton
Brilliant! Strangely the button appearance changes, but that is probably because List has some default appearance settings that ScrollView doesn't bother with. I have already redesigned this part of the app to avoid having two navigation links on one item, but your solution may help with another part of the app where tapping a link inside a List sometimes generates a long navigation path, apparently using the ForEach to build a path using every link inside the list, not just the one tapped, so the Back button has to be clicked maybe 20 times to get back the list view. May I ask, are you on the SwiftUI team?
List on the left vs ScrollView on the right. No other change to code